using System.Collections.Generic;
using Godot;

namespace Arcane.Source.Client.Extensions;

public static class Texture2DExt
{
    public static Texture2D[] Split(this Texture2D tex, int rw, int rh)
    {
        var w = tex.GetWidth();
        var h = tex.GetHeight();

        var col = w / rw;
        var row = h / rh;

        var list = new List<Texture2D>();

        for (int r = 0; r < row; r++)
        {
            for (int c = 0; c < col; c++)
            {
                var atlas = new AtlasTexture
                {
                    Atlas = tex,
                    Region = new(c * rw, r * rh, rw, rh),
                    FilterClip = true,
                };
                list.Add(atlas);
            }
        }
        return [.. list];
    }

    public static Texture2D[] SplitSquares(this Texture2D tex)
    {
        var w = tex.GetWidth();
        var h = tex.GetHeight();
        if (w == h) return [tex];
        var size = Mathf.Min(w, h);
        return tex.Split(size, size);
    }

    public static Texture2D[] SplitSquares(this Texture2D tex, int size) => tex.Split(size, size);

    public static Color AverageColor(this Texture2D tex)
    {
        var w = tex.GetWidth();
        var h = tex.GetHeight();
        var img = tex.GetImage();
        var cnt = 0;
        var r = 0.0f;
        var g = 0.0f;
        var b = 0.0f;
        for (int y = 0; y < h; y++)
        {
            for (int x = 0; x < w; x++)
            {
                var color = img.GetPixel(x, y);
                if (color.A < 0.1f) continue;
                r += color.R;
                g += color.G;
                b += color.B;
                cnt += 1;
            }
        }

        return new(r / cnt, g / cnt, b / cnt);
    }
}